package com.jhf.youke.wechat.adapter.web;

import com.jhf.youke.core.entity.Response;
import com.jhf.youke.wechat.app.executor.WxAppService;
import com.jhf.youke.wechat.domain.model.dto.GetOpenIdByCodeDto;
import com.jhf.youke.wechat.domain.model.dto.WxPayDto;
import com.jhf.youke.wechat.domain.model.dto.WxRefundDto;
import com.jhf.youke.wechat.domain.model.vo.UserInfoVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author RHJ
 */
@Slf4j
@Api(tags = "微信支付")
@RestController
@RequestMapping("/wx")
public class WxController {

    @Resource
    private WxAppService wxAppService;

    @ApiOperation("小程序获取openId")
    @PostMapping("/getOpenIdByCode")
    public Response<String> getOpenIdByCode(@RequestBody @Validated GetOpenIdByCodeDto dto) {
        try {
            return Response.ok(wxAppService.getOpenIdByCode(dto.getCode()));
        } catch (Exception e) {
            return Response.fail(e.getMessage());
        }
    }

    @ApiOperation("公众号和小程序获取支付下单参数")
    @PostMapping("/jsApiPay")
    public Response<Map<String, String>> jsApiPay(@RequestBody @Validated WxPayDto dto) {
        try {
            return Response.ok(wxAppService.jsApiPay(dto));
        } catch (Exception e) {
            return Response.fail(e.getMessage());
        }
    }

    @RequestMapping(value = "/payNotify", method = {org.springframework.web.bind.annotation.RequestMethod.POST, org.springframework.web.bind.annotation.RequestMethod.GET})
    public void payNotify(HttpServletRequest request, HttpServletResponse response) {
        wxAppService.payNotify(request, response);
    }

    @ApiOperation("退款")
    @PostMapping("/refund")
    public Response<Boolean> refund(@RequestBody @Validated WxRefundDto dto) {
        try {
            return Response.ok(wxAppService.refund(dto));
        } catch (Exception e) {
            return Response.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "获取微信用户信息")
    @PostMapping(value = "/getUserInfoByOpenId")
    public Response<UserInfoVo> getUserInfoByToken(@RequestBody Map<String, Object> map) {
        return Response.ok(wxAppService.getUserInfoByOpenId(map));
    }

}
